package org.jeecg.modules.wmhb.controller;

import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.wmhb.entity.WmPurchaseOrderDetail;
import org.jeecg.modules.wmhb.entity.WmPurchaseOrderDetailDy;
import org.jeecg.modules.wmhb.service.IWmPurchaseOrderDetailDyService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecg.modules.wmhb.vo.WmPurchaseOrderDetailDyResult;
import org.jeecg.modules.wmhb.vo.WmPurchaseOrderDetailResult;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.base.controller.JeecgController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.apache.shiro.authz.annotation.RequiresPermissions;

 /**
 * @Description: 电仪订货明细
 * @Author: jeecg-boot
 * @Date:   2025-02-26
 * @Version: V1.0
 */
@Api(tags="电仪订货明细")
@RestController
@RequestMapping("/wmhb/wmPurchaseOrderDetailDy")
@Slf4j
public class WmPurchaseOrderDetailDyController extends JeecgController<WmPurchaseOrderDetailDy, IWmPurchaseOrderDetailDyService> {
	@Autowired
	private IWmPurchaseOrderDetailDyService wmPurchaseOrderDetailDyService;
	
	/**
	 * 分页列表查询
	 *
	 * @param wmPurchaseOrderDetailDy
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	//@AutoLog(value = "电仪订货明细-分页列表查询")
	@ApiOperation(value="电仪订货明细-分页列表查询", notes="电仪订货明细-分页列表查询")
	@GetMapping(value = "/list")
	public Result<IPage<WmPurchaseOrderDetailDy>> queryPageList(WmPurchaseOrderDetailDy wmPurchaseOrderDetailDy,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<WmPurchaseOrderDetailDy> queryWrapper = QueryGenerator.initQueryWrapper(wmPurchaseOrderDetailDy, req.getParameterMap());
		Page<WmPurchaseOrderDetailDy> page = new Page<WmPurchaseOrderDetailDy>(pageNo, pageSize);
		IPage<WmPurchaseOrderDetailDy> pageList = wmPurchaseOrderDetailDyService.page(page, queryWrapper);
		return Result.OK(pageList);
	}
	
	/**
	 *   添加
	 *
	 * @param wmPurchaseOrderDetailDy
	 * @return
	 */
	@AutoLog(value = "电仪订货明细-添加")
	@ApiOperation(value="电仪订货明细-添加", notes="电仪订货明细-添加")
	@RequiresPermissions("wmhb:purchase_order_detail_dy:add")
	@PostMapping(value = "/add")
	public Result<String> add(@RequestBody WmPurchaseOrderDetailDy wmPurchaseOrderDetailDy) {
		wmPurchaseOrderDetailDyService.save(wmPurchaseOrderDetailDy);
		return Result.OK("添加成功！");
	}
	
	/**
	 *  编辑
	 *
	 * @param wmPurchaseOrderDetailDy
	 * @return
	 */
	@AutoLog(value = "电仪订货明细-编辑")
	@ApiOperation(value="电仪订货明细-编辑", notes="电仪订货明细-编辑")
	@RequiresPermissions("wmhb:purchase_order_detail_dy:edit")
	@RequestMapping(value = "/edit", method = {RequestMethod.PUT,RequestMethod.POST})
	public Result<String> edit(@RequestBody WmPurchaseOrderDetailDy wmPurchaseOrderDetailDy) {
		wmPurchaseOrderDetailDyService.updateById(wmPurchaseOrderDetailDy);
		return Result.OK("编辑成功!");
	}

	 /**
	  * 批量到货
	  *
	  * @param ids
	  * @param factArriveTime
	  * @return
	  */
	 @AutoLog(value = "采购订货-批量到货")
	 @ApiOperation(value = "采购订货-批量到货", notes = "采购订货-批量到货")
	 @RequiresPermissions("wmhb:purchase_order_detail:arriveBatch")
	 @RequestMapping(value = "/arriveBatch", method = {RequestMethod.PUT, RequestMethod.POST})
	 public Result<String> arriveBatch(@RequestParam(name = "ids", required = true) String ids, @RequestParam(name = "factArriveTime", required = true) String factArriveTime) {
		 List<String> idList = Arrays.asList(ids.split(","));
		 if(idList.isEmpty()){
			 return Result.error("ids参数为空");
		 }

		 wmPurchaseOrderDetailDyService.arriveBatch(idList, factArriveTime);
		 return Result.OK("操作成功!");
	 }

	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "电仪订货明细-通过id删除")
	@ApiOperation(value="电仪订货明细-通过id删除", notes="电仪订货明细-通过id删除")
	@RequiresPermissions("wmhb:purchase_order_detail_dy:delete")
	@DeleteMapping(value = "/delete")
	public Result<String> delete(@RequestParam(name="id",required=true) String id) {
		wmPurchaseOrderDetailDyService.removeById(id);
		return Result.OK("删除成功!");
	}
	
	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "电仪订货明细-批量删除")
	@ApiOperation(value="电仪订货明细-批量删除", notes="电仪订货明细-批量删除")
	@RequiresPermissions("wmhb:purchase_order_detail_dy:deleteBatch")
	@DeleteMapping(value = "/deleteBatch")
	public Result<String> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.wmPurchaseOrderDetailDyService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功!");
	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "电仪订货明细-通过id查询")
	@ApiOperation(value="电仪订货明细-通过id查询", notes="电仪订货明细-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<WmPurchaseOrderDetailDy> queryById(@RequestParam(name="id",required=true) String id) {
		WmPurchaseOrderDetailDy wmPurchaseOrderDetailDy = wmPurchaseOrderDetailDyService.getById(id);
		if(wmPurchaseOrderDetailDy==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(wmPurchaseOrderDetailDy);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param wmPurchaseOrderDetailDy
    */
    @RequiresPermissions("wmhb:purchase_order_detail_dy:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, WmPurchaseOrderDetailDy wmPurchaseOrderDetailDy) {
        return super.exportXls(request, wmPurchaseOrderDetailDy, WmPurchaseOrderDetailDy.class, "电仪订货明细");
    }

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequiresPermissions("wmhb:purchase_order_detail_dy:importExcel")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
		for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
			// 获取上传文件对象
			MultipartFile file = entity.getValue();
			Integer sheetNum = 1;
			Workbook workbook = null;
			try {
				workbook = WorkbookFactory.create(file.getInputStream());
				sheetNum = workbook.getNumberOfSheets();//读取sheet的数量
			} catch (Exception e) {
				throw new RuntimeException(e.getMessage());
			}

			ImportParams params = new ImportParams();
			params.setStartSheetIndex(0); //从第几个sheet页开始读取
			params.setSheetNum(sheetNum); //读取几个sheet页
			params.setTitleRows(1);       //标题不能为空，否则跳过该行
			params.setHeadRows(1);
			params.setNeedSave(false);
			try(InputStream inputStream = file.getInputStream()) {
				List<WmPurchaseOrderDetailDy> list = ExcelImportUtil.importExcel(inputStream, WmPurchaseOrderDetailDy.class, params);
				WmPurchaseOrderDetailDyResult wmPurchaseOrderDetailDyResult = uploadOrderProcess(list);
				return Result.ok(wmPurchaseOrderDetailDyResult);
			} catch (Exception e) {
				log.error(e.getMessage(), e);
				throw new RuntimeException(e.getMessage());
			} finally {
				try {
					workbook.close();
					file.getInputStream().close();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
		return Result.error("文件导入失败！");
    }

	 private WmPurchaseOrderDetailDyResult uploadOrderProcess(List<WmPurchaseOrderDetailDy> list) {
		 LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		 List<WmPurchaseOrderDetailDy> newList = new ArrayList<>();
		 SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
		 String batchNo = format.format(new Date());
		 Integer successNum = 0;
		 Integer failNum = 0;
		 try {
			 Integer i = 0;
			 for (WmPurchaseOrderDetailDy bomNode : list) {
				 i++;
				 //判断是否读取到金蝶采购订单号字段，没有说明不是电仪订货明细模板
				 if(StringUtils.isEmpty(bomNode.getJdOrderNo()) && i == 1){
					 throw new RuntimeException("模板错误");
				 }

				 //如果没有这两个字段，跳过该行
				 if(StringUtils.isEmpty(bomNode.getJdOrderNo()) && StringUtils.isEmpty(bomNode.getJdName())){
					 continue;
				 }

				 //识别订货日期
				 if(!StringUtils.isEmpty(bomNode.getOrderDate())) {
					 if(isNumeric(bomNode.getOrderDate())) {
						 bomNode.setOrderDate(convertDaysToDate(Integer.parseInt(bomNode.getOrderDate())));
					 }
					 else{
						 bomNode.setResult("订货日期识别失败");
						 bomNode.setStatus("fail");
						 newList.add(bomNode);
						 failNum++;
						 continue;
					 }
				 }

				 //识别到货时间
				 if(!StringUtils.isEmpty(bomNode.getFactArriveTime())) {
					 if(isNumeric(bomNode.getFactArriveTime())) {
						 bomNode.setFactArriveTime(convertDaysToDate(Integer.parseInt(bomNode.getFactArriveTime())));
					 }
					 else{
						 bomNode.setResult("到货时间识别失败");
						 bomNode.setStatus("fail");
						 newList.add(bomNode);
						 failNum++;
						 continue;
					 }
				 }

				 //序号判断，序号为唯一判断值
				 if (StringUtils.isEmpty(bomNode.getSeriesNo())) {
					 //bomNode.setResult("物资申请编号缺失");
					 //bomNode.setStatus("fail");
					 //newList.add(bomNode);
					 //failNum++;
					 //continue;
				 }

				 //如果有需求数量而无数量
				 if (StringUtils.isEmpty(bomNode.getQuantity()) && !StringUtils.isEmpty(bomNode.getQuantity2())){
					 bomNode.setQuantity(bomNode.getQuantity2());
				 }

				 //没有到货数量字段时，到货数量等于数量
				 if(StringUtils.isEmpty(bomNode.getArriveQuantity())){
					 bomNode.setArriveQuantity(bomNode.getQuantity());
				 }

				 //判断是否重复导入
				 if(!StringUtils.isEmpty(bomNode.getSeriesNo())) {
					 //如果有序号，则根据序号判断唯一性
					 List<WmPurchaseOrderDetailDy> wmPurchaseOrderDetailDyList = wmPurchaseOrderDetailDyService.searchBySeriesNoAndRemark(bomNode.getSeriesNo(), bomNode.getRemark());
					 if (!wmPurchaseOrderDetailDyList.isEmpty()) {
						 bomNode.setResult("更新成功");
						 bomNode.setStatus("success");
						 newList.add(bomNode);
						 successNum++;
						 //更新数据
						 wmPurchaseOrderDetailDyService.updateBySeriesNoAndRemark(bomNode);
						 continue;
					 }
				 }
				 else if(!StringUtils.isEmpty(bomNode.getContractNo())){
					 //如果没有序号，有合同号，则根据合同号和金蝶名称判断唯一性
					 List<WmPurchaseOrderDetailDy> wmPurchaseOrderDetailDyList = wmPurchaseOrderDetailDyService.searchByContractAndJdName(bomNode.getContractNo(), bomNode.getJdName());
					 if (!wmPurchaseOrderDetailDyList.isEmpty()) {
						 bomNode.setResult("更新成功");
						 bomNode.setStatus("success");
						 newList.add(bomNode);
						 successNum++;
						 //更新数据
						 wmPurchaseOrderDetailDyService.updateByContractAndJdName(bomNode);
						 continue;
					 }
				 }
				 else if(!StringUtils.isEmpty(bomNode.getJdOrderNo())){
					 //如果没有序号，有金蝶订单号，则根据金蝶订单号和金蝶名称判断唯一性
					 List<WmPurchaseOrderDetailDy> wmPurchaseOrderDetailDyList = wmPurchaseOrderDetailDyService.searchByJdOrderAndJdName(bomNode.getContractNo(), bomNode.getJdName());
					 if (!wmPurchaseOrderDetailDyList.isEmpty()) {
						 bomNode.setResult("更新成功");
						 bomNode.setStatus("success");
						 newList.add(bomNode);
						 successNum++;
						 //更新数据
						 wmPurchaseOrderDetailDyService.updateByJdOrderAndJdName(bomNode);
						 continue;
					 }
				 }

				 //插入数据
				 bomNode.setResult("导入成功");
				 bomNode.setStatus("success");
				 bomNode.setBatchNo(batchNo);
				 bomNode.setUserId(sysUser.getId());
				 bomNode.setUsername(sysUser.getRealname());
				 successNum++;
				 wmPurchaseOrderDetailDyService.save(bomNode);
				 newList.add(bomNode);
			 }
		 } catch (Exception e) {
			 throw new RuntimeException(e.getMessage());
		 }

		 WmPurchaseOrderDetailDyResult wmPurchaseOrderDetailDyResult = new WmPurchaseOrderDetailDyResult();
		 wmPurchaseOrderDetailDyResult.setPurchaseOrderDetailList(newList);
		 wmPurchaseOrderDetailDyResult.setBatchNo(batchNo);
		 wmPurchaseOrderDetailDyResult.setResult("导入成功"+ successNum + "条，导入失败" + failNum + "条");
		 return wmPurchaseOrderDetailDyResult;
	 }

	 private String convertDaysToDate(int totalDays) {
		 Date javaDate = DateUtil.getJavaDate((double) totalDays);
		 return new SimpleDateFormat("yyyy-MM-dd").format(javaDate);
	 }

	 private Boolean isNumeric(String str) {
		 return str.matches("\\d+"); // 正则表达式 \d 是数字字符，+ 表示一次或多次。
	 }

}
